#include "DeviceController.h"
#include "DeviceWorker.h"
#include <QDebug>

DeviceController* DeviceController::m_instance = nullptr;
QMutex DeviceController::m_mutex;

DeviceController* DeviceController::instance()
{
    if (m_instance == nullptr) {
        QMutexLocker locker(&m_mutex);
        if (m_instance == nullptr) {
            m_instance = new DeviceController();
        }
    }
    return m_instance;
}

void DeviceController::destroyInstance()
{
    QMutexLocker locker(&m_mutex);
    if (m_instance != nullptr) {
        delete m_instance;
        m_instance = nullptr;
    }
}

DeviceController::DeviceController(QObject *parent)
    : QObject(parent)
    , m_worker(new DeviceWorker)
    , m_initialized(false)
{
    // 将工作对象移动到工作线程
    m_worker->moveToThread(&m_workerThread);

    // 连接信号和槽
    connect(this, &DeviceController::initRequested, m_worker, &DeviceWorker::init);
    connect(this, &DeviceController::connectRequested, m_worker, &DeviceWorker::connectToDevice);
    connect(this, &DeviceController::disconnectRequested, m_worker, &DeviceWorker::disconnectFromDevice);
    connect(this, &DeviceController::commandRequested, m_worker, &DeviceWorker::sendDeviceCommand);

    // 连接工作线程的信号到主线程的信号
    connect(m_worker, &DeviceWorker::connected, this, &DeviceController::connected);
    connect(m_worker, &DeviceWorker::disconnected, this, &DeviceController::disconnected);
    connect(m_worker, &DeviceWorker::errorOccurred, this, &DeviceController::errorOccurred);
    connect(m_worker, &DeviceWorker::processParametersReceived, this, &DeviceController::processParametersReceived);
    connect(m_worker, &DeviceWorker::commandResponseReceived, this, &DeviceController::commandResponseReceived);
    connect(m_worker, &DeviceWorker::commandDataResponseReceived, this, &DeviceController::commandDataResponseReceived);

    // 连接立即查询数据信号
    connect(m_worker, &DeviceWorker::queryDataImmediatelyReceived, this, &DeviceController::queryDataReceived);

    connect(m_worker, &DeviceWorker::initialized, this, [this]() {
        m_initialized = true;
        emit initialized();
    });

    // 启动工作线程
    m_workerThread.start();
}

DeviceController::~DeviceController()
{
    // 断开所有外部信号连接
    this->disconnect();

    // 清理工作线程
    if (m_worker && m_workerThread.isRunning()) {
        QMetaObject::invokeMethod(m_worker, "cleanup", Qt::BlockingQueuedConnection);
        QThread::msleep(50);

        m_workerThread.quit();
        if (!m_workerThread.wait(1000)) {
            m_workerThread.terminate();
            m_workerThread.wait();
        }
    }

    delete m_worker;
    m_worker = nullptr;
}

void DeviceController::initialize()
{
    emit initRequested();
}

void DeviceController::connectToDevice(const QString &host, quint16 port)
{
    if (!m_initialized) {
        emit errorOccurred("Controller not initialized. Call initialize() first.");
        return;
    }
    emit connectRequested(host, port);
}

void DeviceController::disconnectFromDevice()
{
    if (!m_initialized) {
        emit errorOccurred("Controller not initialized. Call initialize() first.");
        return;
    }
    emit disconnectRequested();
}

bool DeviceController::isConnected() const
{
    return true;
}

void DeviceController::sendCommand(DeviceProtocol::IPCCommand command, const QVariantMap &params)
{
    if (!m_initialized) {
        emit errorOccurred("Controller not initialized. Call initialize() first.");
        return;
    }
    emit commandRequested(command, params);
}
